package com.sskj.fabi.ui.activity;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.box.inputfilter.MoneyValueFilter;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.fabi.R;
import com.sskj.fabi.R2;
import com.sskj.fabi.bean.FabiPayWayBean;
import com.sskj.fabi.component.DaggerUserDataComponent;
import com.sskj.fabi.presenter.PublishActivityPresenter;
import com.sskj.fabi.util.TipFabiUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.FabiBuySellEnum;
import com.sskj.lib.bean.PayTypeEnum;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.AppCircleCheckUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;

@Route(path = RConfig.FABI_PUBLISH)
public class PublishActivity extends BaseActivity<PublishActivityPresenter> {
    @BindView(R2.id.left_sell_ll)
    LinearLayout leftSellLl;
    @BindView(R2.id.right_buy_ll)
    LinearLayout rightBuyll;
    @BindView(R2.id.ivRecord)
    ImageView ivRecord;
    @BindView(R2.id.tvDesc)
    TextView tvDesc;
    @BindView(R2.id.etNum)
    EditText etNum;
    @BindView(R2.id.etMin)
    EditText etMin;
    @BindView(R2.id.etMax)
    EditText etMax;
    @BindView(R2.id.etPrice)
    EditText etPrice;
    @BindView(R2.id.etRemark)
    EditText etRemark;
    @BindView(R2.id.remark_layout)
    LinearLayout remarkLayout;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.tvAddPayType)
    TextView tvAddPayType;
    @BindView(R2.id.llPayType)
    LinearLayout llPayType;
    @BindView(R2.id.btOrder)
    Button btOrder;

    @BindView(R2.id.back_img)
    ImageView backImg;
    @BindView(R2.id.publish_sell)
    TextView publishSell;
    @BindView(R2.id.left_view)
    View leftView;
    @BindView(R2.id.publish_buy)
    TextView publishBuy;
    @BindView(R2.id.right_view)
    View rightView;
    @Autowired
    boolean isBuy = false;

    private String[] titles = {App.INSTANCE.getString(R.string.fabi_publishActivity1) + FabiBuySellEnum.BUY.getTitle(), App.INSTANCE.getString(R.string.fabi_publishActivity1) + FabiBuySellEnum.SELL.getTitle()};
    private SlimAdapter slimAdapter;
    private HashMap<String, Boolean> payMap = new HashMap<>();

    @Inject
    UserViewModel userViewModel;
    private UserData userData;

    @Override
    protected int getLayoutId() {
        return R.layout.fabi_activity_publish;
    }

    @Override
    public PublishActivityPresenter getPresenter() {
        return new PublishActivityPresenter();
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        changeUI();
        ClickUtil.click(backImg, () -> {
            finish();
        });
        ClickUtil.click(leftSellLl, () -> {
            if (!AppCircleCheckUtil.checkAuth(this, userData)) {  // 高级认证
                return;
            }
            isBuy = false;
            changeUI();
        });
        ClickUtil.click(rightBuyll, () -> {
            isBuy = true;
            changeUI();
        });
        initRecy();
//        ClickUtil.click(tvDesc, () -> {
//            TipUtil.getSureCancelTip(this, App.INSTANCE.getString(R.string.fabi_publishActivity2), App.INSTANCE.getString(R.string.fabi_publishActivity3), App.INSTANCE.getString(R.string.fabi_publishActivity4), () -> {
//                mPresenter.cancelShop();
//            });
//        });
        ClickUtil.click(btOrder, () -> {
            if (checkParam()) {
                TipFabiUtil.showPublish(this, isBuy,
                        etPrice.getText().toString(),
                        etNum.getText().toString(), str -> {
                            mPresenter.requsetPublish(isBuy,
                                    etNum.getText().toString(),
                                    etMin.getText().toString(),
                                    etMax.getText().toString(),
                                    etPrice.getText().toString(),
                                    payMap.get("wx") == null ? 0 : (payMap.get("wx") ? 1 : 0),
                                    payMap.get("alipay") == null ? 0 : (payMap.get("alipay") ? 1 : 0),
                                    payMap.get("backcard") == null ? 0 : (payMap.get("backcard") ? 1 : 0),
                                    etRemark.getText().toString(), str[0]);
                        });
            }
        });
        ClickUtil.click(ivRecord, () -> {
            ARouter.getInstance().build(RConfig.FABI_PUBLISH_RECORD).navigation();
        });
        ClickUtil.click(tvAddPayType, () -> {
            ARouter.getInstance().build(RConfig.PAY_PAY_TYPE).navigation();
        });
        etNum.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(6)});
        etMin.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(2)});
        etMax.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(2)});
        etPrice.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(2)});
    }

    private void changeUI() {
        publishBuy.setTextColor(getResources().getColor(isBuy ? R.color.fabi_618 : R.color.fabi_8e9));
        publishSell.setTextColor(getResources().getColor(isBuy ? R.color.fabi_8e9 : R.color.fabi_618));
        leftView.setVisibility(!isBuy ? View.VISIBLE : View.GONE);
        rightView.setVisibility(isBuy ? View.VISIBLE : View.GONE);
        btOrder.setText(isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle());
        etNum.setHint(String.format(App.INSTANCE.getString(R.string.fabi_publishActivity5), isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle()));
        etPrice.setHint(String.format(App.INSTANCE.getString(R.string.fabi_publishActivity6), isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle()));
        tvDesc.setText(String.format(App.INSTANCE.getString(R.string.fabi_publishActivity7), isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle()));
    }

    @Override
    protected void onResume() {
        if (mPresenter != null) {
            mPresenter.requsetPayWayList();
        }
        super.onResume();
    }

    @Override
    protected void initData() {
        mPresenter.requsetPayWayList();
        mPresenter.requestUnitPrice();
    }

    private boolean checkParam() {
        if (TextUtils.isEmpty(etNum.getText())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_publishActivity8));
            return false;
        }
        if (Double.valueOf(etNum.getText().toString())<=0) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_publishActivity9));
            return false;
        }
        if (TextUtils.isEmpty(etPrice.getText())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_publishActivity15));
            return false;
        }
        if (Double.valueOf(etPrice.getText().toString())<=0) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_publishActivity10));
            return false;
        }
        if (TextUtils.isEmpty(etMin.getText())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_publishActivity11));
            return false;
        }
        if (TextUtils.isEmpty(etMax.getText())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_publishActivity12));
            return false;
        }

        if (Double.valueOf(etMin.getText().toString()) > Double.valueOf(etMax.getText().toString())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_publishActivity13));
            return false;
        }

        if ((payMap.get("wx") == null || !payMap.get("wx")) && (payMap.get("alipay") == null || !payMap.get("alipay")) && (payMap.get("backcard") == null || !payMap.get("backcard"))) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_publishActivity14));
            return false;
        }

        return true;
    }

    private void initRecy() {

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(this)
                .setFirstDraw(false)
                .setLastDraw(false)
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 1))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.fabi_232))
        );
        slimAdapter = SlimAdapter.create().register(R.layout.fabi_recy_item_pay_way, new SlimInjector<FabiPayWayBean>() {
            @Override
            public void onInject(FabiPayWayBean data, IViewInjector injector, List payloads) {
                injector.text(R.id.tvPayType, data.getTip())
                        .image(R.id.ivPayType, PayTypeEnum.getByType(data.getType()).getRes())
                        .with(R.id.checkbox, view -> {
                            CheckBox checkBox = (CheckBox) view;
                            checkBox.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.fabi_selector_checkbox, 0);
                        })
                        .checkChangeListener(R.id.checkbox, (buttonView, isChecked) -> {
                            payMap.put(data.getType(), isChecked);
                        });
            }
        });
        slimAdapter.attachTo(recyclerView).updateData(new ArrayList());

    }

    public void updatePayWay(List<FabiPayWayBean> data) {
        Flowable.fromIterable(data).filter(fabiPayWayBean -> fabiPayWayBean.getStatus() == 1).toList().subscribe(fabiPayWayBeans -> slimAdapter.updateData(fabiPayWayBeans));
    }

    public void publishSuccess() {
        RxBus.getDefault().send(RxBusCode.FABI_DATING_REFRESH);

        if (isBuy) {
            RxBus.getDefault().send(RxBusCode.FABI_DATING_SELL);
        } else {
            RxBus.getDefault().send(RxBusCode.FABI_DATING_BUY);
        }
        finish();
    }

    public void updatePrice(String price) {
        etPrice.setText(price);
    }

    public void cancelShopSuccess() {
        finish();
    }

}
